import 'dart:io' show File;

import 'package:dio/dio.dart' as dio;
import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import 'oss_utils.dart';

///文件上传
class OssFileUpload {
  ///阿里oss文件上传
  static Future<String> aliOssUpload(
      {required File file,
      required String saveKey,
      required String accessKeyId,
      required String accessKeySecret,
      required String securityToken,
      required String cdnUrl}) async {
    //表单需要的参数: AccessKeyId、AccessKeySecret、SecurityToken;
    String fileName = file.path.lastIndexOf('/') > -1 ? file.path.substring(file.path.lastIndexOf('/') + 1) : file.path;
    String filename = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    String imageName = fileName.substring(0, fileName.lastIndexOf("."));
    dio.FormData formData = dio.FormData.fromMap({
      //文件名，随意
      'Filename': imageName + filename,
      //"可以填写文件夹名（对应于oss服务中的文件夹）/" + fileName
      'key': saveKey + imageName + filename, //上传后的文件名
      'policy': OssUtil.policy,
      //Bucket 拥有者的AccessKeyId。
      'OSSAccessKeyId': accessKeyId,
      //让服务端返回200，不然，默认会返回204
      'success_action_status': "200",
      'signature': OssUtil.instance!.getSignature(accessKeySecret),
      //临时用户授权时必须，需要携带后台返回的security-token
      'x-oss-security-token': securityToken,
      //上传图片所需要的
      'x-oss-content-type': "image/jpeg",
      'file': await dio.MultipartFile.fromFile(file.path, filename: fileName),
      //必须放在参数最后
    });
    //然后通过存储地址直接把表单(formdata)上传上去;
    dio.Dio dio2 = dio.Dio();
    dio2.options.responseType = dio.ResponseType.plain;
    try {
      dio.Response response = await dio2.post(cdnUrl, data: formData);
      if (response.statusCode == 200) {
        return saveKey+imageName+filename;
      }
      debugPrint(response.headers.toString());
    } on dio.DioError catch (e) {
      SmartDialog.dismiss();
      SmartDialog.showToast("上传图片失败,请重新选择您要上传的图片");
      return "";
    }
     return "";
  }
}
